package cn.itsource.controller;

import cn.itsource.utils.JDBCUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

//账目接口API
@RestController
public class AccountController {

    //前端传来的数据，保存到t_account表
    @PostMapping(value="/save")
    public Map save(@RequestBody Map<String, Object> param){
        Map<String, Object> result = new HashMap<>();
        JDBCUtils.addAccount(param);
        result.put("result", "true");
        result.put("message", "操作成功");
        return result;
    }

    //查询用户所有记账记录
    @PostMapping(value = "/list")
    public Map listPost(@RequestBody Map<String, Object> param){
        Map<String, Object> result = new HashMap<>();
        param.put("current_year", "2021");
        param.put("current_month", "10");
        //1、查询首页头部信息，也就是某年某月的总收入和总开支
        param.put("account_type", "1");//账目类型（1：收入；2：支出）
        BigDecimal shouruNum = JDBCUtils.getUserAccount(param);//获取总收入

        param.put("account_type", "2");//账目类型（1：收入；2：支出）
        BigDecimal zhichuNum = JDBCUtils.getUserAccount(param);//获取总支出

        //获取当前用户所有记账记录
        List<Map<String, Object>> userAccountList =  JDBCUtils.getUserAccountDetail(param);
        //按照time字段进行分组
        Map<String, List<Map<String, Object>>> newMap = userAccountList.stream().collect(Collectors.groupingBy(x -> x.get("time").toString()));

        //封装返回值给前端
        result.put("totalShouru", shouruNum);
        result.put("totalZhichu", zhichuNum);
        result.put("userAccountList", newMap);
        return result;
    }

    //测试接口
    @GetMapping("/hello")
    public String helloWorld(){
        return "hello world";
    }
}
